package com.wvmi.gmall.product.exception;

import com.wvmi.gmall.common.exception.BizCodeEnum;
import com.wvmi.gmall.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述:   <br>
 *
 * @author Wuminming <br>
 * 创建时间: 2023-11-15 15:26 <br>
 * <p>
 * Copyright: 2013 - 2023 www.szwcyq.com Inc. All rights reserved. <br>
 * 注意：本内容仅限于深圳市微创云启科技有限公司内部传阅，禁止外泄以及用于其他的商业目的<br>
 */
@RestControllerAdvice(basePackages = "com.wvmi.gmall.product.controller")
public class ExceptionHandlerController {
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerArgValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String, Object> errorMap = new HashMap<>(bindingResult.getFieldErrors().size());
        bindingResult.getFieldErrors().forEach(b-> errorMap.put(b.getField(),b.getDefaultMessage()));
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",errorMap);
    }

    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable throwable){
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
